package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.TYHException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //小程序 带着code 过来了
        String openid=getOpenid(userLoginDTO.getCode());
        //1 通过code 查询有没有openid  //判断openid是否为空，如果为空表示登录失败，抛出业务异常

        //判断查询出来的OpenId是否为空
        if (StringUtils.isBlank(openid)){
            //如果为空 则直接抛出异常
            throw new TYHException("OpenId不存在 请重试");
        }

        User user=userMapper.selectByOpenId(openid);


        //判断当前是否为新用户
        //如果为新用户 则给他添加信息
        if (user==null){
            user=User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            //将此新用户添加到数据库中
            userMapper.insert(user);
        }
        return user;
    }

    private String getOpenid(String code) {
        Map<String,String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

        //调用微信接口服务，获取当前微信用户的openid
        String json = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);
        //将json 转为 对象 获取id
        User user = JSON.parseObject(json, User.class);
        //获取她的 openid
        String openid = user.getOpenid();
        return openid;
    }
}





















